package net.mhelvens.deltaprofiles;

import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

public class DeltaProfilesDB {
    private static final String TAG = DeltaProfilesDB.class.getSimpleName();
    
    public static final String MAX_ID = "9223372036854775807";

	////////////////////////////////////////////////////////////////////////////
    // Singleton code                                                         //
	////////////////////////////////////////////////////////////////////////////

	static private DeltaProfilesDB _instance;
	static private Context mContext;
	
	static public void setContext(Context ctx) {
		mContext = ctx;
	}
	
	static public DeltaProfilesDB get() {
		assert(mContext != null);
		
		if (_instance == null)
			_instance = new DeltaProfilesDB();
		
		return _instance;
	}
	
	////////////////////////////////////////////////////////////////////////////
    // Database Helpers                                                       //
	////////////////////////////////////////////////////////////////////////////
	
    private static final int DATABASE_VERSION = 1;
    
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    
    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_data, null, DATABASE_VERSION);
        }
        
        private String getDatabaseQueries() throws IOException {
            InputStream is = mContext.getResources().openRawResource(R.raw.tables);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            return new String(buffer);
        }
        
        @Override
        public void onCreate(SQLiteDatabase db) {
        	try {
				for (String query : getDatabaseQueries().split("\n;")) {
					query = query.trim();
					if (!query.isEmpty()) {
						Log.d(TAG, query);
						db.execSQL(query);
					}
				}
			} catch (SQLException e) {
				e.printStackTrace();
	            throw new RuntimeException(e);
			} catch (IOException e) {
				e.printStackTrace();
	            throw new RuntimeException(e);
			}
        }
        
        @Override
		public void onOpen(SQLiteDatabase db) {
			super.onOpen(db);
			if (!db.isReadOnly()) {
				db.execSQL("PRAGMA foreign_keys             = ON ;");
				db.execSQL("PRAGMA recursive_triggers       = ON ;");
				db.execSQL("PRAGMA ignore_check_constraints = OFF;");
			}
		}

		@Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.e(TAG, "onUpgrade'd " + oldVersion + " to " + newVersion + "; This should not happen yet!");
            assert false;
        }
    }

	////////////////////////////////////////////////////////////////////////////
    // Tables and Columns                                                     //
	////////////////////////////////////////////////////////////////////////////
    

    //==========================================================================
    static final String DATABASE_data             = "data";
    //==========================================================================
    static final String TABLE_effects             = "effects";
    //--------------------------------------------------------------------------
    static final String KEY_effect_id             = BaseColumns._ID;
    static final String KEY_effect_source         = "source";
    static final String KEY_effect_data           = "data";
    //==========================================================================
    static final String TABLE_rule_effects        = "rule_effects";
    //--------------------------------------------------------------------------
    static final String KEY_rule                  = "rule";
    static final String KEY_effect                = "effect";
    //==========================================================================
    
    
	////////////////////////////////////////////////////////////////////////////
    // General Methods                                                        //
	////////////////////////////////////////////////////////////////////////////

    private DeltaProfilesDB() throws SQLException {
        mDbHelper = new DatabaseHelper(mContext);
        mDb = mDbHelper.getWritableDatabase();
    }
    
    SQLiteDatabase db() {
    	return mDb;
    }
    
    public void close() {
        mDbHelper.close();
    }
    
}
